<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="search-input" type="text" placeholder="请输入城市名">
    </div>
    <div class="search-content" ref="content" v-show="keyword">
      <ul>
        <li class="search-item border-bottom" v-for="item of list"
            @click="handleIndexCity(item.name)">{{ item.name }}</li>
        <li class="search-item border-bottom" v-show="handleShow">
          没有找到匹配项
        </li>
      </ul>
    </div>
  </div>

</template>

<script>
  import BS from 'better-scroll'

    export default {
        name: "search",
      props:{
        cities:{
          type:Object
        }
      },
      data() {
          return {
            keyword:"",
            list:[],
            timer:null,
            contentShow:false
          }
      },
      computed : {
        handleShow() {

            return this.list.length || this.contentShow

        }
      },
      mounted() {
          this.scroll = new BS(this.$refs.content)
      },
      methods:{
        handleIndexCity(city){
          this.$store.commit('changeCity',city)
          this.$router.push('/')
        }
      },
      watch:{
          keyword(){
            if (this.timer) {
              clearTimeout(this.timer)
            }
            if (!this.keyword) {
              this.list = []
              return
            }
            this.timer = setTimeout( () => {
              const result = []
              for (let i in this.cities) {
                this.cities[i].forEach((item) => {
                  if (item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) > -1) {
                    result.push(item)
                  }
                  this.list = result
                })
              }
            },10)
          }
      }
    }
</script>

<style lang="stylus" scoped>
  @import "~css/common.styl"

  .search
    /*overflow: hidden*/
    height:.72rem
    line-height:.72rem

    background-color: $bgColor
    padding:.1rem

    .search-input
      width:100%
      height:.62rem
      line-height:.62rem
      text-align:center
      color:#666
      padding:0 .1rem
      border-radius: .06rem
      box-sizing:border-box

  .search-content
    z-index:1
    overflow: hidden
    position: absolute
    top:1.78rem
    left:0
    right:0
    bottom:0
    background-color: #eee
    .search-item
      line-height:.64rem
      padding-left:.2rem
      background-color: #fff
      color: #666
</style>
